<?php
class Main_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    /* --------------------begin 页面所有所需的信息 ------------------------ */
    //获取当天商品信息
    function getGoodsArray(){
        $date = date("Y-m-d");//日期：当天
        $this->db->select('c.id,c.publishDate,c.picture,c.title,c.goodsUrl,c.desc,c.originalPrice,c.currentPrice,c.cateID,c.saledNum,c.goodsID,c.comefrom,c.saygood,a.shortName,c.shared,c.collected,c.isTwoBorder,a.id a_id,a.userName');
        $this->db->from('content c');
        $this->db->join('admin a', 'c.updater = a.userName', 'left');
        $this->db->where(array('c.publishDate'=>$date, 'c.status'=>1, 'c.isDel !='=>1));
        $this->db->order_by('c.sort ASC,c.id ASC');
        $query = $this->db->get();
        $goodsArray = $query->result_array();
        //如果没有数据 ，取前一天的数据
        if (!$goodsArray) {
            $date = date("Y-m-d",strtotime("-1 day"));//日期：前一天
        	$this->db->select('c.id,c.publishDate,c.picture,c.title,c.goodsUrl,c.desc,c.originalPrice,c.currentPrice,c.cateID,c.saledNum,c.goodsID,c.comefrom,c.saygood,a.shortName,c.shared,c.collected,c.isTwoBorder,a.id a_id,a.userName');
            $this->db->from('content c');
            $this->db->join('admin a', 'c.updater = a.userName', 'left');
            $this->db->where(array('c.publishDate'=>$date, 'c.status'=>1, 'c.isDel !='=>1));
            $this->db->order_by('c.sort ASC,c.id ASC');
            $query = $this->db->get();
            $goodsArray = $query->result_array();
        }
        return array($goodsArray,$date);
    }
    //根据说说推广获取的商品
    function firstgoods($id){
    	$this->db->select('c.id,c.publishDate,c.picture,c.title,c.goodsUrl,c.desc,c.originalPrice,c.currentPrice,c.cateID,c.saledNum,c.goodsID,c.comefrom,c.saygood,a.shortName,c.shared,c.collected,c.isTwoBorder,a.id a_id,a.userName');
    	$this->db->from('content c');
    	$this->db->join('admin a', 'c.updater = a.userName', 'left');
    	$this->db->where('c.id',$id);
    	$query = $this->db->get();
    	$goodsInfo = $query->row_array();
    	
    	switch ($goodsInfo['cateID']) {
    		case 6:
    			$goodsInfo['cateCss']="picture_lingshi";
    			$goodsInfo['type']="lingshi";
    			break;
    		case 1:
    			$goodsInfo['cateCss']="picture_nvzhuang";
    			$goodsInfo['type']="nvzhuang";
    			break;
    		case 5:
    			$goodsInfo['cateCss']="picture_baobao";
    			$goodsInfo['type']="baobao";
    			break;
    		case 2:
    			$goodsInfo['cateCss']="picture_xiezi";
    			$goodsInfo['type']="xiezi";
    			break;
    		case 7:
    			$goodsInfo['cateCss']="picture_peishi";
    			$goodsInfo['type']="peishi";
    			break;
    		case 4:
    			$goodsInfo['cateCss']="picture_meizhuang";
    			$goodsInfo['type']="meizhuang";
    			break;
    		default:
    			$goodsInfo['cateCss']="picture_icon1";
    			$goodsInfo['type']="nvzhuang";
    			break;
    	}
    	//头像
    	//virtualuser SELECT * FROM virtualuser WHERE id>(1*4) LIMIT 4
    	$day = date("j");
    	$this->db->select("pic");
    	$this->db->where("id >",$day*4);
    	$this->db->limit(4);
    	$query = $this->db->get("virtualuser");
    	$virtualuser = $query->result_array();
    	foreach ($virtualuser as $item){
    		$goodsInfo['virtualuser'][] = $item['pic'];
    	}
    	
    	//真实评论 goodsTrueComment
    	$goodsInfo['commentArray'] = $this->goodsTrueComment($id);
    	//虚拟评论 SELECT * FROM `comment` WHERE cates LIKE "%1%" AND id>(1*4) LIMIT 4
    	$this->db->select("comment");
    	$this->db->like('cates', $goodsInfo['cateID']);
    	$this->db->where("id >",$day*4);
    	$this->db->limit(4);
    	$query = $this->db->get("comment");
    	$comment = $query->result_array();
    	foreach ($comment as $item){
    		$goodsInfo['comments'][] = $item['comment'];
    	}
    	
    	return $goodsInfo;
    }
    //获取商品评论
    function getCommentArray($date){
        //存储过程
        $sql = "CALL updateCommentOrder()";
        $this->db->query($sql);
        //结果
        $this->db->order_by('order','ASC');
        $query = $this->db->get_where('comment',array('turndate'=>$date));
        //$this->sql="SELECT * FROM `comment` WHERE turndate = '".$date."' ORDER BY `order`";
        return $query->result_array();
    }
    //1.获取商品虚拟头像
    function getVirtualUserArray($goodsNum,$date){//表:virtualuser
        $goodsNum_s = $goodsNum*4;//需要的头像数
        //已有的今日头像数
        $rs1 = $this->getVirtualUserByCondition(array('turndate'=>$date,'status'=>1));
        if($rs1[0]==$goodsNum_s){//数量已经够了
            return $rs1[1];
        }else{//数量不错
            $this->db->update('virtualuser',array("turndate"=>"2014-01-01"),array("turndate"=>$date));//删除今天的
            //昨天的头像
            $needDate = date('Y-m-d',strtotime("-1 day",strtotime($date)));
            $rs2 = $this->getVirtualUserByCondition(array('turndate'=>$needDate,'status'=>1));
            if($rs2[0]>0){//昨天有数据
                //需要的头像
                $rs3 = $this->getVirtualUserByCondition(array('id >'=>$rs2[2]['id'],'status'=>1), $goodsNum_s);
                if($rs3[0]==$goodsNum_s){
                    //修改数据库
                    $this->updateVirtualUserByCondition(array("id <="=>$rs3[2]['id'],"id >"=>$rs2[2]['id']), array('turndate' => $date));
                    /* $this->db->where(array("id <="=>$rs3[2]['id'],"id >"=>$rs2[2]['id']));
                    $this->db->update('virtualuser', array('turndate' => $date)); */
                    return $rs3[1];
                }else{
                    //表结尾不足的情况
                    //需要补充的数量
                    $replenishNum = $goodsNum_s-$rs3[0];
                    $rs4 = $this->getVirtualUserByCondition(array('status'=>1), $replenishNum);
                    //合并成Comments
                    $Virtual_rs = array_merge($rs3[1],$rs4[1]);
                    foreach ($Virtual_rs as $key=>$item){
                        $commentsIDArray[] = $item['id'];//更改的id合集
                    }
                    $this->updateVirtualUserByCondition(array("id",$commentsIDArray), array('turndate' => $date), true);
                    /* $this->db->where_in('id',$commentsIDArray);
                    $this->db->update('virtualuser', array('turndate' => $date)); */
                    return $Virtual_rs;
                }
            }else{
                //前 $goodsNum_s 条
                $rs5 = $this->getVirtualUserByCondition(array('status'=>1), $goodsNum_s);
                $this->updateVirtualUserByCondition(array("id <="=>$rs5[2]['id']), array('turndate' => $date));
                /* $this->db->where(array("id <="=>$rs5[2]['id']));
                $this->db->update('virtualuser', array('turndate' => $date)); */
                return $rs5[1];
            }
        }
        
    }
    //2.获取虚拟头像通过日期
    function getVirtualUserByCondition($whereArray,$limit=FALSE){
    	$this->db->order_by("sort","asc");
        //$this->db->order_by('id','ASC');
        if ($limit) {
        	$query = $this->db->get_where('virtualuser',$whereArray,$limit);
        }else {
            $query = $this->db->get_where('virtualuser',$whereArray);
        }
        $VirtualNum = $query->num_rows();//数量
        $Virtual_rs = $query->result_array();//结果
        $Virtual_last = $query->last_row('array');
        return array($VirtualNum,$Virtual_rs,$Virtual_last);
    }
    //更改头像表 by 条件
    function updateVirtualUserByCondition($whereArray,$updateCol,$isWhereIn=FALSE){
        if ($isWhereIn) {
        	$this->db->where_in($whereArray[0],$whereArray[1]);
        }else {
            $this->db->where($whereArray);
        }
        $this->db->update('virtualuser', $updateCol);
        //排序
        if ($isWhereIn) {
        	$this->db->where_in($whereArray[0],$whereArray[1]);
        }else {
        	$this->db->where($whereArray);
        }
        $this->db->set("sort","ROUND(rand()*1000)",FALSE);
        $this->db->update('virtualuser');
    }
    //产品真实评论
    function goodsTrueComment($id){
        $this->db->order_by('id DESC');
        $query = $this->db->get_where('comment2',array('contentid' => $id),10);
        return $query->result_array();
    }
    //商品的点击
    function AjaxGoodsClick($id){
    	$this->db->set("clickNum","IFNULL(clickNum+1,1)",false);
    	$this->db->where("id",$id);
    	$this->db->update("content");
    	return $this->db->affected_rows();
    }
    //底部导言
    function bottomword(){
    	$this->db->select("b.updater,b.content,a.shortName");
    	$this->db->from("bottomwords b");
    	$this->db->join('admin a', 'b.updater = a.userName', 'left');
    	$this->db->order_by("b.pdate DESC");
    	$this->db->limit(1);
    	$query = $this->db->get();
    	return $query->row_array();
    }
    //底部链接
    function bottomlinks(){
    	//父类
    	$this->db->where('parentid','0');
    	$query = $this->db->get('buttomlinks');
    	$parent = $query->result_array();
    	//子类
    	$this->db->where('parentid >','0');
    	$query = $this->db->get('buttomlinks');
    	$children = $query->result_array();
    	//整理
    	foreach ($parent as $key1=>$item1){
    		foreach ($children as $key2=>$item2){
    			if ($item1['id']==$item2['parentid']) {
    				$parent[$key1]['child'][]=$item2;
    			}
    		}
    	}
    	//
    	return $parent;
    }
    /* --------------------end   页面所有所需的信息 ------------------------ */
    /* --------------------begin 用户提交评论------------------------ */
    //用户提交评论
    function AjaxCommentSubmit($goodsid,$comment,$userTouxiang,$ip){
    	$data=array('date'=>date("y-m-d"),
    	                'contentid'=>$goodsid,
    	                'userid'=>$this->session->userdata('openid'),
    	                'userip'=>$ip,
    	                'comment'=>$comment,
    	                'pic'=>$userTouxiang
    	);
    	$this->db->insert('comment2',$data);
    	$changeRow = $this->db->affected_rows();
    	return $changeRow?array('ret'=>1):array('ret'=>0);
    }
    //黑名单
    function AjaxGetForbiddenId(){
        $this->db->select("OpenId");
        $query = $this->db->get_where('ForbiddenIds',array('OpenId'=>$this->session->userdata('openid')),1);
        $forbidArray = $query->row_array();
        return isset($forbidArray['OpenId'])?$forbidArray['OpenId']:FALSE;
    }
    /* --------------------end 用户提交评论------------------------ */
    /* --------------------分享收藏------------------------ */
    function AjaxCollectedShared($id,$action){
    	if ($action==1) $this->db->set("shared","shared+1",FALSE);
    	if ($action==2) $this->db->set("collected","collected+1",FALSE);
    	$this->db->where("id",$id);//更改分享数
    	$this->db->update("content");
    	$changeRow = $this->db->affected_rows();
    	$rs['ret']=$changeRow?1:0;
    	//添加收藏
    	if ($action==2) {
    		//是否收藏
    	    $this->db->where(array('user'=>$this->session->userdata('openid'),'contentid'=>$id,'from'=>1));
    		$query = $this->db->get("usercollected",1);
    	    $collectedNum = $query->num_rows();
    	    if ($collectedNum) {
    	    	$rs['iscollect']=0;
    	    }else {//添加数据
    	    	$data = array('user'=>$this->session->userdata('openid'),'contentid'=>$id);
    	    	$this->db->insert('usercollected', $data);
    	    	$rs['iscollect']=1;
    	    }
    	}
    	return $rs;
    }
    /* --------------------------------------------- 留言 ------------------------------------------ */
    function AjaxCollectedLeaveMessage($message,$userTxInfo){
    	//添加数据
    	$data = array(
    			'openid'=>$this->session->userdata('openid'),
    			'figureurl'=>$userTxInfo['figureurl'],
    			'date' => date("Y-m-d"),
    			'message' => $message,
    			'nickname' => $userTxInfo['nickname']
    	);
    	$affect_row = $this->db->insert('leavelmessage', $data);
    	return array("ret"=>$affect_row,'msg'=>$affect_row?'留言成功咯\(^o^)/':'留言失败⊙﹏⊙');
    }
    
}